package com.liao.cloudstorage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liao.cloudstorage.entity.FileObj;
import com.liao.cloudstorage.mapper.FileObjMapper;
import com.liao.cloudstorage.service.IBucketService;
import com.liao.cloudstorage.service.IFileObjService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liao
 * @since 2019-04-29
 */
@Service
public class FileObjServiceImpl extends ServiceImpl<FileObjMapper, FileObj> implements IFileObjService {

    @Resource
    private FileObjMapper fileObjMapper;
    private final IBucketService bucketService;

    @Autowired
    public FileObjServiceImpl(IBucketService bucketService) {
        this.bucketService = bucketService;
    }

    @Override
    public List<FileObj> getAllFile() {
        return fileObjMapper.selectList(null);
    }

    /**
     * 刪除文件同时对存储桶进行操作
     *
     * @param id 文件id
     * @return 是否删除成功
     */
    @Override
    public boolean autoRemoveFile(int id) {
        FileObj fileObj = fileObjMapper.selectById(id);
        bucketService.autoRemoveFile(fileObj.getBucketName(), fileObj.getObjectSize());
        int i = fileObjMapper.deleteById(id);
        return i == 1;
    }

    @Override
    public FileObj getFileObjByFileName(String objName) {
        List<FileObj> fileObjs = fileObjMapper.selectList(new QueryWrapper<FileObj>().eq("object_name", objName));
        return fileObjs.get(0);
    }

    @Override
    public FileObj getFileObjByBucketAndFileName(String bucketName, String fileName) {
        List<FileObj> fileObjList = fileObjMapper.selectList(new QueryWrapper<FileObj>().eq("bucket_name", bucketName).eq("object_name", fileName));
        return fileObjList.get(0);
    }
}
